import { apiGetOrderShare, apiGetClickOrderRelay, apiGetMessageNotice, getUpdateLevelByUid } from '../../api/index'
import { submitFromData, getRoute } from '../../common/js/mixin'
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    downTime: true,
    count: 0, // 设置 计数器 初始为0
    sourceid: 0,
    user: 1, // 1自己 2他人
    authority: 0,
    showHelpMoney: false,
    commend: true,
    helped: false,
    relayStatus: true,
    tapShare: false,
    showProgress: false,
    shareData: {},
    showData: [],
    show: '',
    id: '',
    index: 0,
    hour: '00',
    min: '00',
    sec: '00',
    type: '',
    isHide: true,
    canvasImgs: []
  },
  // 判断是否授权
  changeAuthStatus (e) {
    this.setData({
      commend: e.detail.status
    })
    this.getData()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(options)
    this.data.type = options.type || ''
    this.screenRatio = wx.getSystemInfoSync().windowWidth / 375
    let user
    if (options.source_uid && (options.source_uid - 0) !== (wx.getStorageSync('uid') - 0)) {
      user = 2
    } else {
      user = 1
    }
    this.id = options.id
    this.setData({
      navHeight: getApp().globalData.navHeight,
      iPad: getApp().globalData.iPad,
      user,
      type: this.data.type
    })
    if (options.source_uid) {
      this.init(options.source_uid)
    }
    this.drawProgressbg()
    this.getData()
    this.getAnimation()
    this.times = setInterval(
      () => {
        this.animations()
      }, 6000)
  },
  // 0-9倒计
  selectNum () {
    let ms = 9
    this.time = setInterval(() => {
      if (ms >= 0) {
        this.setData({
          ms: ms
        })
        ms--
      } else {
        ms = 9
      }
    }, 100)
  },
  init (id) {
    getUpdateLevelByUid({ source_uid: id }).then(
      res => {
        console.log(res)
      }
    )
  },
  getData () {
    apiGetOrderShare({ _id: this.id }).then(
      res => {
        for (let i = 0; i < res.data.order_share_list.length; i++) {
          let data = res.data.order_share_list[i].uid
          if (data === wx.getStorageSync('uid') - 0) {
            this.setData({
              helped: true
            })
          }
        }
        this.creatTime = res.data.create_time + (res.data.valid_time * 60)
        const nowTime = new Date().getTime() / 1000
        let downTime = true
        // 接力完成 停止计时
        if (res.data.order_has_commission === res.data.total_share_commission || this.creatTime < nowTime) {
          this.clearAllTime()
          downTime = false
        } else {
          this.timeDown()
        }
        // 画图
        this.countInterval(res.data)
        this.setData({
          downTime,
          shareData: res.data,
          helpList: res.data.order_share_list
        })
        wx.stopPullDownRefresh()
      }
    )
  },
  // 倒计时
  timeDown () {
    let s = this.creatTime - new Date().getTime() / 1000
    if (s > 0) {
      this.timer = setTimeout(() => {
        let h = Math.floor(s / 3600 % 24)
        let min = Math.floor(s / 60 % 60)
        let sec = Math.floor(s % 60)
        h = this.add(h)
        min = this.add(min)
        sec = this.add(sec)
        this.setData({
          hour: h,
          min,
          sec
        })
        this.timeDown(s)
      }, 1000)
    } else {
      this.clearAllTime()
      this.setData({
        downTime: false
      })
      this.getData()
      const route = this.getRoute()
      if (route && route.init) {
        route.init()
      }
    }
  },
  add (m) {
    return m < 10 ? '0' + m : m
  },
  toHome () {
    wx.switchTab({
      url: '../shopping/shopping'
    })
  },
  // 立即提现
  toVipCenter () {
    wx.navigateTo({
      url: '../distribution-center/distribution-center'
    })
  },
  showShares () {
    this.setData({
      tapShare: true,
      showProgress: true
    })
  },
  // 为他接力
  helpOther (e) {
    this._submitFrom(e.detail.formId)
    if ((this.data.shareData.uid - 0) === (wx.getStorageSync('uid') - 0)) {
      wx.showToast({
        title: '不能为自己接力哦~',
        icon: 'none'
      })
    } else {
      apiGetClickOrderRelay({ _id: this.id }).then(
        res => {
          if (res.code === 0) {
            this.setData({
              helpData: res.data,
              relayStatus: false,
              showHelpMoney: true,
              showProgress: true,
              canvasImg: ''
            })
            this.getData()
          }
        }
      )
    }
  },
  isClose () {
    this.setData({
      showHelpMoney: false,
      tapShare: false
    })
    setTimeout(() => {
      this.setData({
        showProgress: false
      })
    }, 300)
  },
  // 生成图片
  creatImg () {
    wx.navigateTo({
      url: `../create-relay-img/index?id=${this.id}`
    })
  },
  // 规则说明
  toRule () {
    wx.navigateTo({
      url: '../relay-rule/index'
    })
  },
  // ........................................画圆/............................................./
  drawProgressbg () {
    // 使用 wx.createContext 获取绘图上下文 context
    let ctx = wx.createCanvasContext('canvasProgressbg')
    ctx.setLineWidth(20)// 设置圆环的宽度
    ctx.setStrokeStyle('#EEEEEE')// 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath()// 开始一个新的路径
    ctx.arc(75 * this.screenRatio, 75 * this.screenRatio, 65 * this.screenRatio, 0, 2 * Math.PI, false)
    // 设置一个原点(100,100)，半径为90的圆的路径到当前路径
    ctx.stroke() // 对当前路径进行描边
    ctx.draw(false, (success) => {
      if (success.errMsg.indexOf('ok') !== -1) {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          canvasId: 'canvasProgressbg',
          success: (res) => {
            this.setData({
              isLoaded: true,
              canvasImgBg: res.tempFilePath
            })
          }
        })
      }
    })
  },
  drawCircle (step) {
    console.log('开始画了')
    step = step * 2
    let context = wx.createCanvasContext('canvasProgress')
    // 设置渐变
    let gradient = context.createLinearGradient(200, 100, 100, 200)
    gradient.addColorStop('0', '#FF4C4C')
    gradient.addColorStop('1.0', '#FF3128')
    context.setLineWidth(20)
    context.setStrokeStyle(gradient)
    context.setLineCap('round')
    context.beginPath()
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(75 * this.screenRatio, 75 * this.screenRatio, 65 * this.screenRatio, -Math.PI / 2, step * Math.PI - Math.PI / 2, false)
    context.stroke()
    context.draw(true, (success) => {
      console.log('画完了')
      if (success.errMsg.indexOf('ok') !== -1) {}
    })
    setTimeout(() => {
      console.log('画完了')
      var images = this.data.canvasImgs
      this.setData({
        canvasImg: ''
      })
      console.log('没有缓存图片')
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'canvasProgress',
        success: (res) => {
          images.push(res.tempFilePath)
          images = images.map((item, index) => {
            if (index < images.length - 1) {
              return ''
            } else { return item }
          })
          this.setData({
            isLoaded: true,
            canvasImg: res.tempFilePath,
            canvasImgs: images
          })
        }
      })
    }, 500)
  },
  countInterval (data) {
    const total = data.total_share_commission - 0
    const orderHas = data.order_has_commission - 0
    if (orderHas <= total && orderHas > 0) {
      this.drawCircle(orderHas / total)
    }
  },
  // 获取用户购物提示
  getAnimation () {
    apiGetMessageNotice().then(
      res => {
        this.setData({
          showData: res.data
        })
      }
    )
  },
  // 动画显示
  animations () {
    this.data.index++
    if (this.data.index === this.data.showData.length) {
      this.data.index = 0
    }
    this.setData({
      show: this.data.showData[this.data.index]
    })
    setTimeout(() => {
      this.setData({
        show: ''
      })
    }, 4000)
  },
  onShow () {
    this.selectNum()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
    this.clearAllTime()
    this.setData({
      tapShare: false
    })
  },
  clearAllTime () {
    clearTimeout(this.timer)
    clearInterval(this.time)
    this.timer = null
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
    this.clearAllTime()
    this.setData({
      tapShare: false
    })
    clearInterval(this.times)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    this.getData()
    this.selectNum()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    return {
      title: '我正在领取红包，帮我接力下也有钱哦～～',
      imageUrl: 'https://cdn.duonadian.com/bg_realy_makecard@3x.png',
      path: `/pages/relay/index?id=${this.data.shareData.id}&source_uid=${this.data.shareData.uid}`
    }
  }
}
getRoute(page)
submitFromData(page)
Page(page)
